package org.example.encrypt.typeHandler;

import cn.hutool.core.util.StrUtil;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.example.encrypt.utils.AESUtil;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 针对字符串类型做加解密
 */
@MappedTypes(String.class)
@MappedJdbcTypes({JdbcType.VARCHAR, JdbcType.LONGNVARCHAR, JdbcType.LONGNVARCHAR})
public class StringTypeHandler extends BaseTypeHandler<String> {

    /**
     * 入参加密
     */
    @Override
    public void setNonNullParameter(PreparedStatement ps, int index, String param, JdbcType jdbcType) throws SQLException {
        if (StrUtil.isNotBlank(param)) {
            ps.setString(index, AESUtil.encrypt(param));
        }
    }

    /**
     * 下面3个都是处理结果集的
     * 返回结果解密
     */
    @Override
    public String getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String columnValue = rs.getString(columnName);
        if (StrUtil.isNotBlank(columnValue)) {
            return AESUtil.decrypt(columnValue);
        }
        return "";
    }

    @Override
    public String getNullableResult(ResultSet rs, int index) throws SQLException {
        String columnValue = rs.getString(index);
        if (StrUtil.isNotBlank(columnValue)) {
            return AESUtil.decrypt(columnValue);
        }
        return "";
    }

    @Override
    public String getNullableResult(CallableStatement cs, int index) throws SQLException {
        String columnValue = cs.getString(index);
        if (StrUtil.isNotBlank(columnValue)) {
            return AESUtil.decrypt(columnValue);
        }
        return "";
    }
}

